package com.edu.bhu.admin.controller.admin;

import java.util.ArrayList;
import java.util.List;

import com.edu.bhu.admin.domain.BikBicycle;
import com.edu.bhu.admin.domain.BikImages;
import com.edu.bhu.admin.service.IBikImagesService;
import com.edu.bhu.common.config.OverallConfig;
import com.edu.bhu.common.utils.StringUtils;
import com.edu.bhu.common.utils.file.FileUploadUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.edu.bhu.common.annotation.Log;
import com.edu.bhu.common.enums.BusinessType;
import com.edu.bhu.admin.service.IBikBicycleService;
import com.edu.bhu.common.core.controller.BaseController;
import com.edu.bhu.common.core.domain.AjaxResult;
import com.edu.bhu.common.utils.poi.ExcelUtil;
import com.edu.bhu.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 单车Controller
 * 
 * @author heyinan
 * @date 2022-03-14
 */
@Controller
@RequestMapping("/admin/bicycle")
public class BikBicycleController extends BaseController
{

    private static final String FILE_DELIMETER = ",";

    private String prefix = "admin/bicycle";

    @Autowired
    private IBikBicycleService bikBicycleService;

    @Autowired
    private IBikImagesService bikImagesService;

    @RequiresPermissions("admin:bicycle:view")
    @GetMapping()
    public String bicycle()
    {
        return prefix + "/bicycle";
    }

    /**
     * 查询单车列表
     */
    @RequiresPermissions("admin:bicycle:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(BikBicycle bikBicycle)
    {
        startPage();
        List<BikBicycle> list = bikBicycleService.selectBikBicycleList(bikBicycle);
        return getDataTable(list);
    }

    /**
     * 进入单车列表页
     */
    @RequiresPermissions("admin:bicycle:view")
    @GetMapping("/bicycleCard")
    public String houseCard()
    {
        return prefix + "/bicycleCard";
    }

    /**
     * 查询单车列表，伴随第一张图片，不显示已经被出租的和停用的
     */
    @RequiresPermissions("admin:bicycle:list")
    @PostMapping("/listWithImg")
    @ResponseBody
    public TableDataInfo listWithImg(BikBicycle bikBicycle)
    {
        //查询时的标记：排除被出租的和停用的
        bikBicycle.getParams().put("listAll","1");
        startPage();
        List<BikBicycle> list = bikBicycleService.selectBikBicycleListWithImg(bikBicycle);
        return getDataTable(list);
    }

    /**
     * 进入某个单车的详细信息页
     */
    @GetMapping("/bicycleInfo/{bikId}")
    public String houseInfo(@PathVariable("bikId") Long bikId, ModelMap mmap)
    {
        //拿到单车信息
        BikBicycle bikBicycle = bikBicycleService.selectBikBicycleByBikId(bikId);
        //获取单车所属的图片列表
        List<BikImages> images = bikImagesService.selectBikImagesListByBikId(bikId);
        mmap.put("bicycle", bikBicycle);
        mmap.put("images", images);
        return prefix + "/bicycleInfo";
    }

    /**
     * 导出单车列表
     */
    @RequiresPermissions("admin:bicycle:export")
    @Log(title = "单车", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(BikBicycle bikBicycle)
    {
        List<BikBicycle> list = bikBicycleService.selectBikBicycleList(bikBicycle);
        ExcelUtil<BikBicycle> util = new ExcelUtil<BikBicycle>(BikBicycle.class);
        return util.exportExcel(list, "单车数据");
    }

    /**
     * 新增单车
     */
    @GetMapping("/add")
    public String add()
    {
        return prefix + "/add";
    }

    /**
     * 新增保存单车
     */
    @RequiresPermissions("admin:bicycle:add")
    @Log(title = "单车", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(BikBicycle bikBicycle)
    {
        return toAjax(bikBicycleService.insertBikBicycle(bikBicycle));
    }

    /**
     * 修改单车
     */
    @RequiresPermissions("admin:bicycle:edit")
    @GetMapping("/edit/{bikId}")
    public String edit(@PathVariable("bikId") Long bikId, ModelMap mmap)
    {
        BikBicycle bikBicycle = bikBicycleService.selectBikBicycleByBikId(bikId);
        mmap.put("bikBicycle", bikBicycle);
        return prefix + "/edit";
    }

    /**
     * 修改保存单车
     */
    @RequiresPermissions("admin:bicycle:edit")
    @Log(title = "单车", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(BikBicycle bikBicycle)
    {
        return toAjax(bikBicycleService.updateBikBicycle(bikBicycle));
    }

    /**
     * 单车状态修改
     */
    @Log(title = "单车", businessType = BusinessType.UPDATE)
    @RequiresPermissions("admin:bicycle:edit")
    @PostMapping("/changeStatus")
    @ResponseBody
    public AjaxResult changeStatus(BikBicycle bikBicycle)
    {
        return toAjax(bikBicycleService.changeStatus(bikBicycle));
    }


    /**
     * 删除单车
     */
    @RequiresPermissions("admin:bicycle:remove")
    @Log(title = "单车", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        return toAjax(bikBicycleService.deleteBikBicycleByBikIds(ids));
    }

    /**
     * 进入图片选择页
     */
    @GetMapping("/selectImage/{bikId}")
    public String selectImage(@PathVariable("bikId") Long bikId, ModelMap mmap)
    {
        BikBicycle bikBicycle = bikBicycleService.selectBikBicycleByBikId(bikId);

        //获取房屋所属的图片列表
        List<BikImages> images = bikImagesService.selectBikImagesListByBikId(bikId);
        mmap.put("bicycle", bikBicycle);
        mmap.put("images", images);
        return prefix + "/selectImage";
    }

    /**
     * 单车添加图片（多图片上传，同时把图片路径保存到数据库）
     */
    @RequiresPermissions("admin:bicycle:edit")
    @Log(title = "单车管理", businessType = BusinessType.GRANT)
    @PostMapping("/selectImage/uploads")
    @ResponseBody
    public AjaxResult uploads(List<MultipartFile> files, Long bikId, int imgNum) throws Exception
    {
        int fileNum = files.size();
        if (fileNum + imgNum > 12)
        {
            return error("图片总数不能超过5张！");
        }
        try
        {
            // 上传文件路径
            String filePath = OverallConfig.getUploadPath();
            List<String> fileNames = new ArrayList<>();
            List<String> urls = new ArrayList<>();
            for (MultipartFile file : files)
            {
                BikImages bikImages = new BikImages();
                // 上传并返回新文件名称
                String fileName = FileUploadUtils.upload(filePath, file);
                bikImages.setImages(fileName);
                bikImages.setBikId(bikId);
                bikImagesService.insertBikImages(bikImages);
            }
            AjaxResult ajax = AjaxResult.success();
            ajax.put("fileNames", StringUtils.join(fileNames, FILE_DELIMETER));
            ajax.put("urls", StringUtils.join(urls, FILE_DELIMETER));
            return ajax;
        }
        catch (Exception e)
        {
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 填写报修信息的弹框
     */
    @RequiresPermissions("admin:bicycle:view")
    @GetMapping("/goAddRepair/{bikId}")
    public String goAddRepair(@PathVariable("bikId") String bikId, ModelMap mmap)
    {
        mmap.put("bikId",bikId);
        return prefix + "/addRepair";
    }


}
